<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>websocket</title>
    <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
</head>
<style>
</style>

<body>
    <input type="text" id="txtInput" />
    <input type="button" value="发送消息" onclick="clickAndsendMessage();" />
    <hr />
    <div id="messageDiv">
    
    </div>
</body>
<script th:inline="javascript">
var websocket = null;
$(function() {
	$('#txtInput').keyup(function(e) {
		if(e && e.keyCode == 13) {
			clickAndsendMessage();
		}
	});
	if(window.WebSocket) {
		websocket = new WebSocket('ws://127.0.0.1:8081/websocket/33578/7893e07add1545519b8cb90dacc3dc7b');
		
		websocket.onerror = function() {
			console.log('websocket发生错误');
		}
		
		websocket.onopen = function() {
			console.log('websocket连接成功', websocket);
		}
		
		websocket.onmessage = function(event) {
			console.log(event.data);
			showMessage(event.data);
		}
		
		websocket.onclose = function() {
			console.log('websocket连接关闭');
			websocket.close();
		}
	}
});

function showMessage(msg) {
	$('#messageDiv').append('<div>' + msg + '</div>');
}
function clickAndsendMessage() {
	var msg = $('#txtInput').val();
	if(msg) {
		websocket.send(msg);
		$('#txtInput').val('');
	}
}
</script>
</html>